import datetime
import threading
from datetime import time
import time
import psutil

from app.modle.models import VirtualMemoryInfo
from app.utils.util import bytes_to_mb,bytes_to_gb
from app.setting.config import MAX_HISTORY
from app.utils.util import get_current_time
class VmMonitor:

    def __init__(self):
        self.memory_history = []
        self.time_history = []
        self._lock = threading.Lock()
        self.last_cache = None  # 新增缓存属性

    # 获取内存使用信息
    async def get_memory_info(self) -> VirtualMemoryInfo:
        """收集内存和网络使用信息"""
        # 获取当前时间和内存使用情况
        current_time = get_current_time()
        mem = psutil.virtual_memory()

        # 更新历史数据
        with self._lock:
            self.memory_history.append(mem.percent)
            self.time_history.append(get_current_time())
            if len(self.memory_history) > MAX_HISTORY:
                self.memory_history.pop(0)

            history = self.memory_history[-20:].copy()

        # 创建内存信息对象
        memory_info = VirtualMemoryInfo(
            vm_total=bytes_to_gb(mem.total),
            vm_available=bytes_to_gb(mem.available),
            vm_used=bytes_to_gb(mem.used),
            vm_free=bytes_to_gb(mem.free),
            vm_timestamp=datetime.datetime.now(),
            vm_percent=round(mem.percent,1)
        )

        # 尝试获取特定于类Unix系统的内存指标
        if hasattr(mem, 'active'):
            memory_info.vm_active = mem.active
        if hasattr(mem, 'inactive'):
            memory_info.vm_inactive = mem.inactive
        if hasattr(mem, 'buffers'):
            memory_info.vm_buffers = mem.buffers
        if hasattr(mem, 'cached'):
            memory_info.vm_cached = mem.cached
        if hasattr(mem, 'shared'):
            memory_info.vm_shared = mem.shared
        if hasattr(mem, 'slab'):
            memory_info.vm_slab = mem.slab
        self.last_cache = memory_info  # 更新缓存
        return memory_info




if __name__ == '__main__':
    a = VmMonitor()








